package cn.edu.hznu.coursework.util;

import org.hibernate.annotations.common.util.StringHelper;
import org.hibernate.cfg.ImprovedNamingStrategy;

public class DatabaseNamingStrategy extends ImprovedNamingStrategy{

	/**
	 * 
	 */
	private static final long serialVersionUID = 2352988571628257636L;

	private final static String TABLE_PREFIX = "t_";
	private final static String COLLECTION_TABLE_SUFFIX = "_mapping";
	private final static String FOREIGNKEY_SUFFIX = "_id";
	
	@Override
	public String classToTableName(String className) {
		return tableName(super.classToTableName(className));
	}

	@Override
	public String propertyToColumnName(String propertyName) {
		// TODO Auto-generated method stub
		return super.propertyToColumnName(propertyName);
	}

	@Override
	public String tableName(String tableName) {
		return tableName.toLowerCase().startsWith(TABLE_PREFIX) ? 
				tableName.toLowerCase() : 
				TABLE_PREFIX.concat(tableName.toLowerCase());
	}

	@Override
	public String columnName(String columnName) {
		// TODO Auto-generated method stub
		return super.columnName(columnName);
	}

	@Override
	public String collectionTableName(String ownerEntity,
			String ownerEntityTable, String associatedEntity,
			String associatedEntityTable, String propertyName) {
		return tableName(new StringBuffer(ownerEntityTable)
				.append("_")
				.append(associatedEntityTable != null ? associatedEntityTable
						: StringHelper.unqualify(propertyName))
				.append(COLLECTION_TABLE_SUFFIX).toString());
	}

	@Override
	public String joinKeyColumnName(String joinedColumn, String joinedTable) {
		// TODO Auto-generated method stub
		return super.joinKeyColumnName(joinedColumn, joinedTable);
	}

	@Override
	public String foreignKeyColumnName(String propertyName,
			String propertyEntityName, String propertyTableName,
			String referencedColumnName) {
		String columnName = super.foreignKeyColumnName(propertyName, propertyEntityName,
				propertyTableName, referencedColumnName);
		return columnName.endsWith(FOREIGNKEY_SUFFIX) ? columnName : columnName + FOREIGNKEY_SUFFIX;
	}
	
}
